import query from './atom/db/query';
import count from './atom/db/count';
import { IBaseTable } from './atom/db/interfaces';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

interface Message {
	filter: {};
	sort: {};
	page_size: 0;
	page_no: 1;
}

interface certifiInfo extends IBaseTable {
	_id:string;                         									//id
	no:string;                          									//编号
	staff_name:string;                  									//员工名称
	staff_number:string;                									//员工编号
	staff_type:string;                  									//员工类型
	deptid:string;                      									//部门编号
	deptname:string;                    									//部门名称
	personal_skill:string;              									//技能名称
	is_special_job:Boolean;              									//是否特种作业
	resume_grade:string;                									//级别
	is_skill_certificate:Boolean;        									//是否技能证
	date_of_issue:number;               									//发证日期
	valitydate:number;                  									//有效期
	enddate:number;                     									//到期日期
	org_name:string;                    									//发证机构
	post_name:string;                   									//适用职务
	memo:string;                        									//备注
	accessory_url:string                									//附件
}


function format(date: number) {
	if (date === null) {
		return '';
	}
	try {
		const _date = new Date(parseFloat(date + ''));
		if (_date) {
			return _date.getFullYear() + '-' + _format(_date.getMonth() + 1) + '-' + _format(_date.getDate());
		}
		return '';
	} catch (error) {
		return '';
	}
}

function _format(d: number) {
	if (d < 10) {
		return '0' + d;
	} else {
		return d;
	}
}

async function atom(msg: Message) {
	const systemid = '6051';
	const { exec, prepare } = query(action_id, session_id, spaceid, systemid);
	const asc: string[] = [];
	const desc: string[] = [];
	if (msg.sort) {
		const key = Object.keys(msg.sort)[0];
		if (msg.sort[key] === -1) {
			desc.push(key);
		} else {
			asc.push(key);
		}
	}
	// 证照信息
	prepare('profession_skill', ["_id","no","staff_name","staff_number","staff_type","deptid","deptname","personal_skill","is_special_jos","resume_grade","is_skill_certificat","date_of_issue","valitydate","enddate","org_name","post_name","memo","accessory_url",], msg.filter, msg.page_size, msg.page_no, asc, desc);
	const [data] = await exec();

	data.forEach((item: certifiInfo) => {
		item['date_of_issue_str'] = format(item.date_of_issue);
		item['valitydate_str'] = format(item.valitydate);
		item['enddate_str'] = format(item.enddate);
	});

	const c = count(action_id, session_id, spaceid, systemid);
	c.prepare('profession_skill', msg.filter);
	const [t] = await c.exec();

	return { dataArray: data, count: t };
}